<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Web原生打印解决方案 | Yanwuhc</title><meta name="author" content="Yanwuhc"><meta name="copyright" content="Yanwuhc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="背景与问题公司web项目采用vue-print-nb插件实现局部html的打印需求，有一天用户反馈一个问题：点击【打印】按钮，在Safari浏览器中无法打开打印弹窗。 经过本地的调试，确实发现了这个问题，但在Chrome中未能复现。打断点调试之后，发现vue-print-nb插件在Safari浏览器执行过程中中断了，但控制台未报任何错误。经过一段时间的debug与尝试，最终放弃了对这个插件的修改，">
<meta property="og:type" content="article">
<meta property="og:title" content="Web原生打印解决方案">
<meta property="og:url" content="https://gitee.com/yanwuhc/little-world.git/2023/06/13/Web-Print/index.html">
<meta property="og:site_name" content="Yanwuhc">
<meta property="og:description" content="背景与问题公司web项目采用vue-print-nb插件实现局部html的打印需求，有一天用户反馈一个问题：点击【打印】按钮，在Safari浏览器中无法打开打印弹窗。 经过本地的调试，确实发现了这个问题，但在Chrome中未能复现。打断点调试之后，发现vue-print-nb插件在Safari浏览器执行过程中中断了，但控制台未报任何错误。经过一段时间的debug与尝试，最终放弃了对这个插件的修改，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/yanwuhc/little-world.git/img/post-cover/print.jpg">
<meta property="article:published_time" content="2023-06-13T10:51:00.000Z">
<meta property="article:modified_time" content="2023-06-13T12:16:00.147Z">
<meta property="article:author" content="Yanwuhc">
<meta property="article:tag" content="Print">
<meta property="article:tag" content="iframe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/yanwuhc/little-world.git/img/post-cover/print.jpg"><link rel="shortcut icon" href="/little-world/img/favicon.png"><link rel="canonical" href="https://gitee.com/yanwuhc/little-world.git/2023/06/13/Web-Print/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/little-world/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/little-world/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: Yanwuhc","link":"链接: ","source":"来源: Yanwuhc","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Web原生打印解决方案',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-06-13 20:16:00'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
          const isLightMode = window.matchMedia('(prefers-color-scheme: light)').matches
          const isNotSpecified = window.matchMedia('(prefers-color-scheme: no-preference)').matches
          const hasNoSupport = !isDarkMode && !isLightMode && !isNotSpecified

          if (t === undefined) {
            if (isLightMode) activateLightMode()
            else if (isDarkMode) activateDarkMode()
            else if (isNotSpecified || hasNoSupport) {
              const now = new Date()
              const hour = now.getHours()
              const isNight = hour <= 6 || hour >= 18
              isNight ? activateDarkMode() : activateLightMode()
            }
            window.matchMedia('(prefers-color-scheme: dark)').addListener(function (e) {
              if (saveToLocal.get('theme') === undefined) {
                e.matches ? activateDarkMode() : activateLightMode()
              }
            })
          } else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/little-world/img/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/little-world/archives/"><div class="headline">文章</div><div class="length-num">2</div></a><a href="/little-world/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/little-world/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/little-world/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/little-world/img/post-cover/print.jpg')"><nav id="nav"><span id="blog-info"><a href="/little-world/" title="Yanwuhc"><span class="site-name">Yanwuhc</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/little-world/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/little-world/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Web原生打印解决方案</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="fa-fw post-meta-icon far fa-calendar-alt"></i><span class="post-meta-label">发表于</span><time datetime="2023-06-13T10:51:00.000Z" title="发表于 2023-06-13 18:51:00">2023-06-13</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/little-world/categories/%E5%89%8D%E7%AB%AF%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/">前端解决方案</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">971</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>3分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Web原生打印解决方案"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="背景与问题"><a href="#背景与问题" class="headerlink" title="背景与问题"></a>背景与问题</h2><p>公司web项目采用<code>vue-print-nb插件</code>实现局部html的打印需求，有一天用户反馈一个问题：点击【打印】按钮，在Safari浏览器中无法打开打印弹窗。</p>
<p>经过本地的调试，确实发现了这个问题，但在Chrome中未能复现。打断点调试之后，发现<code>vue-print-nb插件</code>在Safari浏览器执行过程中中断了，但控制台未报任何错误。经过一段时间的debug与尝试，最终放弃了对这个插件的修改，转向其他解决方案。</p>
<h2 id="探索解决方案"><a href="#探索解决方案" class="headerlink" title="探索解决方案"></a>探索解决方案</h2><p>网上比较主流的打印方案有这么几种：</p>
<ul>
<li>Print.js</li>
<li>vue-print-nb.js</li>
<li>html2canvas + pdf.js 生成图片后导出pdf打印</li>
<li>window.print结合iframe - 原生打印解决方案</li>
</ul>
<p>看了一下原有项目，由于打印的内容在一个单独的vue文件里面；同时，css样式集中在一个style标签上，所以最终考虑决定使用<code>window.print</code>结合iframe原生打印方案。</p>
<h2 id="原理-amp-amp-思路"><a href="#原理-amp-amp-思路" class="headerlink" title="原理&amp;&amp;思路"></a>原理&amp;&amp;思路</h2><p><code>window.print</code>一般对整个页面进行打印，将需要局部打印的html元素放入到iframe中，并调用<code>iframe</code>的print方法，即可实现局部打印的效果。</p>
<h2 id="核心代码块"><a href="#核心代码块" class="headerlink" title="核心代码块"></a>核心代码块</h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">template</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">&quot;print-order&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">button</span> @<span class="attr">click</span>=<span class="string">&quot;handlePrint&quot;</span>&gt;</span>打印<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">&quot;printArea&quot;</span>&gt;</span></span><br><span class="line">      <span class="comment">&lt;!-- 打印区域 --&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">template</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="language-javascript"></span></span><br><span class="line"><span class="language-javascript"><span class="keyword">export</span> <span class="keyword">default</span> &#123;</span></span><br><span class="line"><span class="language-javascript">  <span class="attr">methods</span>: &#123;</span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">handlePrint</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">      <span class="keyword">let</span> printHtml = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&#x27;printArea&#x27;</span>).<span class="property">innerHTML</span>; <span class="comment">//获取指定打印区域</span></span></span><br><span class="line"><span class="language-javascript">      <span class="keyword">let</span> iframe = <span class="variable language_">document</span>.<span class="title function_">createElement</span>(<span class="string">&#x27;iframe&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">      <span class="keyword">var</span> doc = <span class="literal">null</span>;</span></span><br><span class="line"><span class="language-javascript">      iframe.<span class="title function_">setAttribute</span>(<span class="string">&#x27;id&#x27;</span>, <span class="string">&#x27;print-iframe&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">      iframe.<span class="title function_">setAttribute</span>(<span class="string">&#x27;style&#x27;</span>, <span class="string">&#x27;position: absolute; width: 0px; height: 0px;left:-500px;top:-500px;&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">      <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">appendChild</span>(iframe);</span></span><br><span class="line"><span class="language-javascript">      doc = iframe.<span class="property">contentWindow</span>.<span class="property">document</span>;</span></span><br><span class="line"><span class="language-javascript">      <span class="comment">//这里可以自定义样式</span></span></span><br><span class="line"><span class="language-javascript">      doc.<span class="title function_">write</span>(<span class="string">&#x27;&lt;style media=&quot;print&quot;&gt;@page &#123;size: auto; margin: 0 mm;&#125;&lt;/style&gt;&#x27;</span>); <span class="comment">//解决出现页眉页脚和路径的问题</span></span></span><br><span class="line"><span class="language-javascript">      doc.<span class="title function_">write</span>(<span class="variable language_">this</span>.<span class="title function_">getPrintStyle</span>())</span></span><br><span class="line"><span class="language-javascript">      doc.<span class="title function_">write</span>(<span class="string">&#x27;&lt;div style=&quot;margin: 20px auto;&quot;&gt;&#x27;</span> + printHtml + <span class="string">&#x27;&lt;/div&gt;&#x27;</span>);</span></span><br><span class="line"><span class="language-javascript">      doc.<span class="title function_">close</span>();</span></span><br><span class="line"><span class="language-javascript">      iframe.<span class="property">contentWindow</span>.<span class="title function_">focus</span>();</span></span><br><span class="line"><span class="language-javascript">      iframe.<span class="property">contentWindow</span>.<span class="title function_">print</span>(); <span class="comment">// 如果样式不生效，可以试试用setTimeout</span></span></span><br><span class="line"><span class="language-javascript">      <span class="variable language_">document</span>.<span class="property">body</span>.<span class="title function_">removeChild</span>(iframe);</span></span><br><span class="line"><span class="language-javascript">    &#125;,</span></span><br><span class="line"><span class="language-javascript">    <span class="comment">// 注：获取打印样式，必须跟底部的Style标签内容一样。</span></span></span><br><span class="line"><span class="language-javascript">    <span class="title function_">getPrintStyle</span>(<span class="params"></span>) &#123;</span></span><br><span class="line"><span class="language-javascript">      <span class="keyword">return</span> <span class="string">`&lt;style&gt;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        .danView&#123;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          /* 多个自动按页面划分 */</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          page-break-after: always;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        &#125;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        /* 解决safari多出一页的问题 */</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        .danView:last-child&#123;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">            page-break-after: auto;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        &#125;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        .pre-cash-apply &#123;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          line-height: 18px;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript"></span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          /* 强制换行 */</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          word-wrap:break-word;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">          word-break:break-all;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">        &#125;</span></span></span><br><span class="line"><span class="string"><span class="language-javascript">      &lt;/style&gt;`</span></span></span><br><span class="line"><span class="language-javascript">    &#125;,</span></span><br><span class="line"><span class="language-javascript">  &#125;</span></span><br><span class="line"><span class="language-javascript">&#125;</span></span><br><span class="line"><span class="language-javascript"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">style</span> <span class="attr">scoped</span>&gt;</span><span class="language-css"></span></span><br><span class="line"><span class="language-css"><span class="comment">/* 更新这里面的内容，记得更新getPrintStyle方法！！！ */</span></span></span><br><span class="line"><span class="language-css"><span class="selector-class">.danView</span>&#123;</span></span><br><span class="line"><span class="language-css">  <span class="comment">/* 多个自动按页面划分 */</span></span></span><br><span class="line"><span class="language-css">  <span class="attribute">page-break-after</span>: always;</span></span><br><span class="line"><span class="language-css">&#125;</span></span><br><span class="line"><span class="language-css"><span class="comment">/* 解决多出一页的问题 */</span></span></span><br><span class="line"><span class="language-css"><span class="selector-class">.danView</span><span class="selector-pseudo">:last-child</span>&#123;</span></span><br><span class="line"><span class="language-css">  <span class="attribute">page-break-after</span>: auto;</span></span><br><span class="line"><span class="language-css">&#125;</span></span><br><span class="line"><span class="language-css"><span class="selector-class">.pre-cash-apply</span> &#123;</span></span><br><span class="line"><span class="language-css">  <span class="attribute">line-height</span>: <span class="number">18px</span>;</span></span><br><span class="line"><span class="language-css"></span></span><br><span class="line"><span class="language-css">  <span class="comment">/* 强制换行 */</span></span></span><br><span class="line"><span class="language-css">  <span class="attribute">word-wrap</span>:break-word;</span></span><br><span class="line"><span class="language-css">  <span class="attribute">word-break</span>:break-all;</span></span><br><span class="line"><span class="language-css">&#125;</span></span><br><span class="line"><span class="language-css"><span class="comment">/* 更新这里面的内容，记得更新getPrintStyle方法！！！ */</span></span></span><br><span class="line"><span class="language-css"></span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><code>printArea</code>指定了打印区域，需要局部打印的html写在里面。</p>
<p><code>handlePrint</code>用来手动调用打印按钮，主要包括以下逻辑。</p>
<ul>
<li>获取局部需要局部打印的html；</li>
<li>在body中创建一个空iframe；</li>
<li>将html的内容塞进iframe内；</li>
<li>将html的样式表塞进iframe内；</li>
<li>调用iframe中的print方法；</li>
<li>移除body中的iframe。</li>
</ul>
<p>这里有个地方需要说明一下，<code>getPrintStyle</code>用于获取局部打印的css样式。简单处理为直接复制本vue文件<code>style</code>标签上的内容，目前找不到更好的获取方式，便简单处理成这样。</p>
<blockquote>
<p>这样的话会有个缺陷：只要<code>style</code>标签的内容修改了，就需要同步修改<code>getPrintStyle</code>里面的内容。</p>
</blockquote>
<h2 id="值得注意"><a href="#值得注意" class="headerlink" title="值得注意"></a>值得注意</h2><p><code>page-break-after: always;</code>主要用来解决多个打印的分页问题，但在调试的过程中，Safari浏览器总会多出一张空白页，经过研究检索，最终加入以下代码片段：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 解决多出一页的问题 */</span></span><br><span class="line"><span class="selector-class">.danView</span><span class="selector-pseudo">:last-child</span>&#123;</span><br><span class="line">  <span class="attribute">page-break-after</span>: auto;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://gitee.com/yanwuhc/little-world.git">Yanwuhc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://gitee.com/yanwuhc/little-world.git/2023/06/13/Web-Print/">https://gitee.com/yanwuhc/little-world.git/2023/06/13/Web-Print/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://gitee.com/yanwuhc/little-world.git" target="_blank">Yanwuhc</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/little-world/tags/Print/">Print</a><a class="post-meta__tags" href="/little-world/tags/iframe/">iframe</a></div><div class="post_share"><div class="social-share" data-image="/little-world/img/post-cover/print.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="next-post pull-full"><a href="/little-world/2023/06/12/hello-hexo/" title="你好，Hexo"><img class="cover" src="/little-world/img/default-post.JPG" onerror="onerror=null;src='/little-world/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">你好，Hexo</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/little-world/img/avatar.jpg" onerror="this.onerror=null;this.src='/little-world/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Yanwuhc</div><div class="author-info__description">一位野生的前后端开发者。</div></div><div class="card-info-data site-data is-center"><a href="/little-world/archives/"><div class="headline">文章</div><div class="length-num">2</div></a><a href="/little-world/tags/"><div class="headline">标签</div><div class="length-num">2</div></a><a href="/little-world/categories/"><div class="headline">分类</div><div class="length-num">1</div></a></div><a id="card-info-btn" href="https://gitee.com/yanwuhc"><i class="fab fa-gitlab"></i><span>个人仓库</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://blog.csdn.net/weixin_44303404" target="_blank" title="CSDN"><i class="fas fa-book" style="color: #4a7dbe;"></i></a><a class="social-icon" href="mailto:1340951588@qq.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">不断学习中～</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%83%8C%E6%99%AF%E4%B8%8E%E9%97%AE%E9%A2%98"><span class="toc-number">1.</span> <span class="toc-text">背景与问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%8E%A2%E7%B4%A2%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">2.</span> <span class="toc-text">探索解决方案</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E7%90%86-amp-amp-%E6%80%9D%E8%B7%AF"><span class="toc-number">3.</span> <span class="toc-text">原理&amp;&amp;思路</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A0%B8%E5%BF%83%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-number">4.</span> <span class="toc-text">核心代码块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%80%BC%E5%BE%97%E6%B3%A8%E6%84%8F"><span class="toc-number">5.</span> <span class="toc-text">值得注意</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/little-world/2023/06/13/Web-Print/" title="Web原生打印解决方案"><img src="/little-world/img/post-cover/print.jpg" onerror="this.onerror=null;this.src='/little-world/img/404.jpg'" alt="Web原生打印解决方案"/></a><div class="content"><a class="title" href="/little-world/2023/06/13/Web-Print/" title="Web原生打印解决方案">Web原生打印解决方案</a><time datetime="2023-06-13T10:51:00.000Z" title="发表于 2023-06-13 18:51:00">2023-06-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/little-world/2023/06/12/hello-hexo/" title="你好，Hexo"><img src="/little-world/img/default-post.JPG" onerror="this.onerror=null;this.src='/little-world/img/404.jpg'" alt="你好，Hexo"/></a><div class="content"><a class="title" href="/little-world/2023/06/12/hello-hexo/" title="你好，Hexo">你好，Hexo</a><time datetime="2023-06-12T14:45:48.000Z" title="发表于 2023-06-12 22:45:48">2023-06-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('/little-world/img/post-cover/print.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2023 By Yanwuhc</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/little-world/js/utils.js"></script><script src="/little-world/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><div class="js-pjax"></div><script defer="defer" id="ribbon" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-ribbon.min.js" size="150" alpha="0.6" zIndex="-1" mobile="false" data-click="true"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>